package com.ruitu.health_1.ui;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.ruitu.arad.base.BaseActivity;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.arad.view.EditTextCleanView;
import com.ruitu.health_1.R;
import com.ruitu.health_1.mvp.model.UserInfoModel;
import com.ruitu.health_1.mvp.presenter.UserInfoPresent;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.bean.user.Address;
import com.ruitu.router_module.util.ReqUtil;

import java.util.HashMap;
import java.util.Map;

public class AdAdActivity extends BaseActivity<UserInfoPresent.AddressP, UserInfoModel.AddressM> {

    private EditTextCleanView et_tel, et_contacts, et_pc, et_p, et_c, et_r, et_address_details, et_postCode;//电话,收货人,省市区,详细地址,邮政编码
    private CheckBox ck_default;
    private Address address;
    private TextView tv_add_or_edit;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_ad_ad;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initViews() {
        super.initViews();
        Bundle bundle =  getIntent().getExtras();
        if (bundle!=null){
           address = (Address) bundle.get("address");
        }
        et_tel = findViewById(R.id.et_tel);
        et_contacts = findViewById(R.id.et_contacts);
        et_pc = findViewById(R.id.et_pc);
        et_p = findViewById(R.id.et_p);
        et_c = findViewById(R.id.et_c);
        et_r = findViewById(R.id.et_r);
        et_postCode = findViewById(R.id.et_postCode);
        et_address_details = findViewById(R.id.et_address_details);
        ck_default = findViewById(R.id.ck_default);
        tv_add_or_edit = findViewById(R.id.tv_add_or_edit);
        if (address != null) {
            setAddress();
        }
        setOnClickListener(tv_add_or_edit);
    }

    private void setAddress() {
        setHeadTitle("修改地址");
        et_contacts.setText(address.getName());
        et_tel.setText(address.getPhoneNumber());
        et_p.setText(address.getProvince());
        et_c.setText(address.getCity());
        et_r.setText(address.getRegion());
        et_postCode.setText(address.getPostCode());
        et_address_details.setText(address.getDetailAddress());
        tv_add_or_edit.setText("修改");
    }

    public void onAddContacts(View view) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 999);
        } else {
            getContacts();
        }

    }

    private Map<String, String> map;

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (tv_add_or_edit == v) {
            onAdd();
            showProgress();
            if (address == null) {
                p.addAddress(ReqUtil.getBody(map, true));
            } else {
                p.updateAddress(ReqUtil.getBody(map, true));
            }
        }
    }

    public void onAdd() {
        map = new HashMap<>();
        String tel = et_tel.getText().toString();
        String contacts = et_contacts.getText().toString();
        String pc = et_pc.getText().toString();
        String address_details = et_address_details.getText().toString();
        String ps = et_p.getText().toString();
        String c = et_c.getText().toString();
        String r = et_r.getText().toString();
        String postCode = et_postCode.getText().toString();
        String defaultStatus = "0";
        if (ck_default.isChecked()) {
            defaultStatus = "1";
        } else {
            defaultStatus = "0";
        }
        if (tel == null) {
            ToastUtils.showShort("手机号码不能为空");
            return;
        }
        if (contacts == null) {
            ToastUtils.showShort("收货人不能为空");
            return;
        }

        if (p == null & c == null & r == null) {
            ToastUtils.showShort("省市区不能为空");
            return;
        }
        if (address_details == null) {
            ToastUtils.showShort("详细地址不能为空");
        }

        map.put("province", ps);//省
        map.put("city", c);//市
        map.put("region", r);//区
        map.put("defaultStatus", defaultStatus);//是否为默认0不是默认,1是默认
        map.put("detailAddress", address_details);//详细地址
        map.put("memberId", AppHolder.instance().getUser().getId());//用户id
        map.put("name", contacts);//收货人名称
        map.put("postCode", postCode);//邮政编码
        map.put("phoneNumber", tel);//收货人电话

    }

    /**
     * 删除成功回调
     */
    public void deleteSuc() {
        finish();
    }

    private void getContacts() {
        Uri uri = Uri.parse("content://contacts/people");
        Intent intent = new Intent(Intent.ACTION_PICK, uri);
        startActivityForResult(intent, 979);
    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            Logg.i(phone.toString());
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 979) {
            if (data != null) {
                Uri uri = data.getData();
                Logg.i("data: " + data.toString());
                Logg.i("uri: " + uri.toString());

                String[] contacts = getPhoneContacts(uri);
                Logg.i("contacts: " + contacts.toString());
                et_contacts.setText(contacts[0]);
                et_tel.setText(contacts[1].replace(" ", ""));
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 999) {
            if (grantResults[0] >= 0) {
                getContacts();
            }
        }
    }
}
